<template>
  <a-popover placement="bottomLeft" arrow-point-at-center>
    <template #content>
      <div class="header-notice-container">
        <a-row class="header-row">
          <a-col :span="20" class="justify-center">{{$t('layout.noticeContent')}}</a-col>
          <a-col :span="4">{{$t('common.operate')}}</a-col>
        </a-row>
        <a-row
          class="notice-content-container"
          v-for="(item, index) in untreatNoticeList"
          :key="index"
        >
          <a-col :span="20">
            <div
              :class="
                item.notifyType == 1 || item.notifyType == 2
                  ? 'warning'
                  : 'error'
              "
            >
              <exclamation-circle-outlined
                v-if="item.notifyType == 1 || item.notifyType == 2"
              />
              <close-circle-outlined v-else />
            </div>
            <div>
              <p>{{ item.content }}</p>
              <div>
                {{ formatTime(item.createTime, "YYYY-MM-DD HH:mm:ss") }}
              </div>
            </div>
          </a-col>
          <a-col :span="4">
            <span class="primary-operate-tag" @click="closeNotice(item)">{{$t('layout.complete')}}</span>
          </a-col>
        </a-row>
        <div class="no-notice" v-if="!untreatNoticeList.length">{{$t('layout.noNotice')}}</div>
        <div class="all-notice" v-if="untreatNoticeList.length" @click="checkAll">{{$t('layout.lookAll')}}</div>
      </div>
    </template>
    <a-badge :count="untreatNoticeNo" size="small" class="hover-pointer">
      <span class="iconfont icon-xiaoxitixing bell-icon"></span>
    </a-badge>
  </a-popover>
  <promptModal ref="promptModalRef"></promptModal>
</template>

<script>
import { store } from "@/store";
import { mapState } from "vuex";
import { getLocalStorage } from "@/utils";
import { getToken, formatTime } from "@/utils";
import { notification, Button } from "ant-design-vue";
import { h } from "vue";
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import axios from "@/utils/request";
// import { cloneDeep } from 'lodash'
import {
  CloseCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import promptModal from "@/components/productionPrompt/promptModal.vue";
export default {
  data() {
    return {
      hangerLineList: [],
    };
  },
  components: {
    // BellOutlined,
    CloseCircleOutlined,
    ExclamationCircleOutlined,
    promptModal,
  },
  computed: {
    ...mapState({
      untreatNoticeNo: (state) => state.normalData.untreatNoticeNo,
      untreatNoticeList: (state) => state.normalData.untreatNoticeList,
      operateNoticeList: (state) => state.operateData.operateNoticeList,
      tabs: (state) => state.setting.tabs,
    }),
  },
  methods: {
    formatTime,
    close() {
      this.stompClient.disconnect();
      this.wsSocket.close();
    },
    wsConnect() {
      this.wsSocket = new SockJS(`http://10.18.34.11:8081/websocket`);
      this.stompClient = Stomp.over(this.wsSocket);
      const wsHeader = {
        type: "tenant",
        Authorization: getToken(),
      };
      this.stompClient.connect(wsHeader, () => {
        this.stompClient.subscribe("/topic/pc/hangerNotify", async (res) => {
          console.log("🚀 ~ file: headerNotice.vue:100 ~ this.stompClient.subscribe ~ res:", res)
          // console.log('*********************', res)
          let body = res.body ? JSON.parse(res.body) : {};
          let isCurrentMsg = this.hangerLineList.filter(
            (i) => i.lineNo == body.data.lineNo
          ).length;
          if (isCurrentMsg) {
            await store.dispatch("getUntreatNotice");
            this.openNotify(body.data);
          }
        });

        this.stompClient.subscribe(
          "/topic/pc/planningInProductin",
          async (res) => {
            let body =  res.body ? JSON.parse(res.body) : {};
            // console.log(body, "---!!!!planningInProductin!!!!---");
            if (body?.data?.success) {
              // body.data.hanging_pre_management
              this.$refs.promptModalRef.open(body.data.hanging_pre_management);
            }
          }
        );
      });
    },
    async closeNotice(record, noSend) {
      // console.log('________id', record);
      let { id } = record;
      if (!noSend)
        await axios.postAction("/api/hanger/hanger-notify/save", {
          id,
          resolved: 1,
        });
      let ary = [...this.operateNoticeList];
      ary.forEach((i) => {
        if (i == id) notification.close(i);
      });
      ary = ary.filter((i) => i != id);
      store.commit("updateOperateState", {
        operateNoticeList: ary,
      });
      store.dispatch("getUntreatNotice");
    },
    async openNotify(res) {
      // let { id, notifyType, content, resolved } = res;
      // notifyType 0、告警 1、求助 2、呼叫
      let { lineNo, stationNo, id, notifyCode, notifyType, content, resolved } =
        res;
      let type = notifyType == 1 || notifyType == 2 ? "warning" : "error";
      let isShow = resolved != 2;
      let title = "";
      const notifyText = {
        1: "呼叫组长",
        2: "呼叫机修",
        3: "呼叫质量员",
        4: "故障报修",
        5: "取消报修",
        6: "完成报修",
        7: "清除呼叫",
      };
      // title处理
      if (notifyType == 1) {
        title = resolved == 2 ? this.$t('layout.cancelHelp') :  this.$t('layout.helpTips');
      }
      if (notifyType == 2) {
        title = notifyText[notifyCode];
      }
      if (![1, 2].includes(notifyType)) {
        title = this.$t('layout.warning');
      }
      // untreatNoticeList处理
      if (notifyType == 2 && notifyCode == 5) {
        this.untreatNoticeList = this.untreatNoticeList.filter(
          (item) => item.lineNo == lineNo && item.stationNo == stationNo
        );
      }
      if (notifyType == 2 && notifyCode == 7) {
        this.untreatNoticeList = this.untreatNoticeList.filter(
          (item) => item.notifyCode > 3
        );
      }

      // console.log(this.untreatNoticeList)
      // let title = notifyType == 1 ? (resolved == 2 ? "取消求助" : "求助提示") : "警告";
      const key = id;
      let ary = [...this.operateNoticeList];

      if (ary.includes(id)) await this.closeNotice({ id }, true);
      ary.push(id);
      store.commit("updateOperateState", {
        operateNoticeList: Array.from(new Set(ary)),
      });
      notification[type]({
        message: title,
        description: content,
        duration: 0,
        top: "80px",
        btn: () =>
          h("div", [
            h(
              Button,
              {
                size: "small",
                style: {
                  marginRight: "20px",
                  visibility: isShow ? "visible" : "hidden",
                  height: "28px",
                  lineHeight: "28px",
                  padding: "0 18px ",
                },
                onClick: () => notification.close(key),
              },
              { default: () =>  this.$t('layout.later') }
            ),
            h(
              Button,
              {
                size: 'small',
                style: { marginRight: '20px', visibility: isShow ? 'visible' : 'hidden', height: '28px', lineHeight: '28px', padding: '0 18px ' },
                onClick: () => notification.close(key)
              }, { default: () => this.$t('layout.later') }),
            h(Button, {
              type: 'primary',
              size: 'small',
              style: { padding: '0 18px', height: '28px', lineHeight: '28px' },
              onClick: async () => {
                if (resolved != 2) {
                  this.closeNotice({ id: key })
                } else {
                  notification.close(key)
                }
              }
            }, { default: () => resolved == 2 ? this.$t('common.ok') : this.$t('layout.complete') })
          ]),
        key,
      });
    },

    async checkAll() {
      this.$router.push({
        path: "/personalCenter/noticeMsg",
        query: {
          unDo: true,
          refresh: Math.random(),
        },
      });
    },
  },
  created() {
    this.hangerLineList = getLocalStorage("hangerLineList") || [];
    this.wsConnect();
    store.dispatch("getUntreatNotice");
  },
};
</script>